package com.szs.controller;

import com.szs.common.R;
import com.szs.pojo.User;
import com.szs.service.UserService;
import com.szs.util.SMSUtils;
import com.szs.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("输入的手机号为：{}", user.getPhone());

        // 获取手机号
        String phone = user.getPhone();

        // 判断手机号是非为空
        if (StringUtils.isNotEmpty(phone)) {
            // 生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();

            // 发送验证码
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909",
                    "19357928885", code);

            // 保存信息到session
            session.setAttribute(phone, code);
            return R.success("手机短信验证码发送成功");
        }
        return R.error("手机短信验证码发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        return userService.login(map, session);
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
